/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wf3.servlet;

import acceso.hibernate.AQuery;
import acceso.hibernate.AccesoHibernate;
import acceso.servicio.Service_manager;
import acceso.servicio.correo.SCorreo;
import acceso.servlet.Transa_Engine;
import acceso.util.Escritor;
import acceso.util.FePagina;
import acceso.util.Popup;
import acceso.util.Td_autinc;
import acceso.util.Tr_autinc;
import acceso.util.Transaccion;
import acceso.util.WorkflowUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.exception.SQLGrammarException;
import wf.dto.*;
import wf3.hibernate.Aquery2;
import wf3.kernel.TransaManager;
import wf3.kernel.WorkflowFactory;

/**
 *
 * @author Rómulo Galindo Tanta
 */
public class WorkflowPostServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init();
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setContentType("text/html;charset=ISO-8859-1");
        Escritor.escribe_debug(" Ejecutando WFPOST");
        PrintWriter out = response.getWriter();
        try {
            int accion = Integer.parseInt(request.getParameter("xact"));
            switch (accion) {
                case 1: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 1">
                    StatelessSession HSESSION = null;
                    List l = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();

                        long p_id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                        int co_conten = Integer.parseInt(request.getParameter("contenedor"));
                        int p_co_pagina = Integer.parseInt(request.getParameter("co_pagina"));
                        short p_co_pagregori = Short.parseShort(request.getParameter("co_pagreg"));
                        String p_va_pagregori = request.getParameter("va_pagreg");

                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfvalpagpos"));
                        IHQUERY.setLong("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_pagina", p_co_pagina);
                        IHQUERY.setInteger("p_co_conten", co_conten);
                        IHQUERY.setShort("p_co_pagregori", p_co_pagregori);
                        IHQUERY.setString("p_va_pagregori", p_va_pagregori);
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l = IHQUERY.getMquery().list();
                        if (l != null) {
                            out.print(new Gson().toJson(l));
                        } else {
                            out.print("");
                        }
                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 2: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 2">
                    StatelessSession HSESSION = null;
                    List l = null;

                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();

                        long id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                        int p_co_pagina = Integer.parseInt(request.getParameter("co_pagina"));
                        int co_conten = Integer.parseInt(request.getParameter("contenedor"));
                        short p_co_regist = Short.parseShort(request.getParameter("co_regist"));
                        short p_co_pagregori = Short.parseShort(request.getParameter("co_pagreg"));
                        String p_va_pagregori = request.getParameter("va_pagreg");

                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfcompagpos"));
                        IHQUERY.setLong("p_id_frawor", id_frawor);
                        IHQUERY.setInteger("p_co_pagina", p_co_pagina);
                        IHQUERY.setInteger("p_co_conten", co_conten);
                        IHQUERY.setShort("p_co_regist", p_co_regist);
                        IHQUERY.setShort("p_co_pagregori", p_co_pagregori);
                        IHQUERY.setString("p_va_pagregori", p_va_pagregori);
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l = IHQUERY.getMquery().list();
                        if (l != null) {
                            out.print(new Gson().toJson(l));
                        } else {
                            out.print("");
                        }
                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 3: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 3">
                    String res = "";
                    Exception ex = null;
                    try {
                        Object o = session.getAttribute("Error");
                        ex = (o != null) ? (Exception) o : new Exception("");
                        if (ex != null) {
                            int id_frawor = WorkflowUtil.convertir_entero(request.getParameter("p_id_frawor"), 0);
                            int co_pagina = WorkflowUtil.convertir_entero(request.getParameter("p_co_pagina"), 0);
                            int co_conten = WorkflowUtil.convertir_entero(request.getParameter("p_co_conten"), 0);

                            res = getError(ex);

                            session.removeAttribute("Error");

                            if (id_frawor > 0 & co_pagina > 0) {
                                try {
                                    Transa_Engine.Transa_Ins_tbexcept(id_frawor, co_pagina, res);
                                } catch (Exception ep) {
                                    Escritor.escribe_errors("Erro al grabar la excepción:" + ep.getMessage());
                                }
                            } else if (id_frawor > 0 & co_conten > 0) {
                                try {
                                    Transa_Engine.Transa_Ins_tbexcept(id_frawor, co_pagina, res);
                                } catch (Exception ep) {
                                    Escritor.escribe_errors("Erro al grabar la excepción:" + ep.getMessage());
                                }
                            }
                        }
                        out.print(res);
                    } catch (Exception ep) {
                        out.print(ep.getMessage());
                    }
                    // </editor-fold>
                    break;
                }
                case 4: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 4">
                    try {
                        int id_transa = WorkflowUtil.convertir_entero(request.getParameter("transa"));
                        int id_frawor = WorkflowUtil.convertir_entero(request.getParameter("id_frawor"));
                        Date fe_solfin = WorkflowUtil.convertir_fecha(request.getParameter("fe_solfin"));
                        int id_session = request.getSession().getAttribute("US") == null ? 0 : ((acceso.util.UserSesion) request.getSession().getAttribute("US")).getId_sesion();
                        if (id_session > 0) {
                            TransaManager.putQuery(new Aquery2(id_session, id_transa, 0, 0, fe_solfin, Aquery2.TRANSAFIN));
                            String fe_pagina = WorkflowUtil.convertir_string(request.getParameter("fe_pagina"), "A");
                            if (!fe_pagina.contains("A")) {
                                try {
                                    List<FePagina> ls_fe_pagina = new Gson().fromJson(fe_pagina, new TypeToken<List<FePagina>>() {
                                    }.getType());
                                    ls_fe_pagina.stream().forEach((fepagina) -> {
                                        long l_fe_visini = WorkflowUtil.convertir_long(fepagina.getFe_visini(), 0);
                                        long l_fe_visfin = WorkflowUtil.convertir_long(fepagina.getFe_visfin(), 0);
                                        if (l_fe_visini > 0 & l_fe_visfin > 0) {
                                            TransaManager.putQuery(new Aquery2(id_session, id_transa, id_frawor, fepagina.getCo_pagina(), new Date(l_fe_visini), new Date(l_fe_visfin), Aquery2.TRAPAGVIS));
                                        }
                                    });
                                } catch (Exception ep) {
                                    Escritor.escribe_errors("error en wfp-xact:4 ->" + ep.getMessage());
                                    ep.printStackTrace();
                                }
                            }
                        }
                        out.println("OK");
                    } catch (Exception ep) {
                        Escritor.escribe_errors("Error xact:4 ->" + ep.getMessage());
                        ep.printStackTrace();
                    }
                    // </editor-fold>
                    break;
                }
                case 5: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 5">
                    StatelessSession HSESSION = null;
                    Transaction TRANSAX = null;
                    String exception = null;

                    String header = request.getHeader("Content-Type");
                    System.out.println("[header: " + header + "]");

                    long id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                    int co_conten = Integer.parseInt(request.getParameter("co_conten"));
                    int co_conori = Integer.parseInt(request.getParameter("co_conori"));
                    int p_co_pagina = Integer.parseInt(request.getParameter("co_pagina"));
                    short p_co_pagbot = Short.parseShort(request.getParameter("co_pagbot"));
                    int propag = Integer.parseInt(request.getParameter("propag"));
                    int borrar = Integer.parseInt(request.getParameter("borrar"));

                    java.util.Enumeration enu = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
                        enu = request.getParameterNames();

                        if (borrar == 1) {
                            Escritor.escribe_frawor("eliminando parametros");
                            AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfdel_tbpagreg"));
                            IHQUERY.setLong("p_id_frawor", id_frawor);
                            IHQUERY.setInteger("p_co_pagina", p_co_pagina);
                            IHQUERY.getMquery().uniqueResult();
                        }

                        while (enu.hasMoreElements()) {
                            String o = enu.nextElement().toString();
                            String mv = request.getParameter(o);
                            if (o.startsWith("co_conpar")) {
                                AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfdel_tbconpar"));
                                IHQUERY.setLong("p_id_frawor", id_frawor);
                                IHQUERY.setInteger("p_co_conten", co_conten);
                                IHQUERY.setShort("p_co_conpar", Short.parseShort(o.replaceAll("co_conpar_", "")));
                                IHQUERY.getMquery().uniqueResult();

                                IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfins_tbconpar"));
                                IHQUERY.setLong("p_id_frawor", id_frawor);
                                IHQUERY.setInteger("p_co_conten", co_conten);
                                IHQUERY.setShort("p_co_conpar", Short.parseShort(o.replaceAll("co_conpar_", "")));
                                IHQUERY.setString("p_va_conpar", mv);
                                Escritor.escribe_frawor("--> " + IHQUERY.getQuery());
                                IHQUERY.getMquery().uniqueResult();
                            } else if (o.startsWith("va_regist")) {
                                String[] reg = o.replaceAll("va_regist_", "").split("_");

                                AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfins_tbpagreg"));
                                IHQUERY.setLong("p_id_frawor", id_frawor);
                                IHQUERY.setInteger("p_co_pagina", Integer.parseInt(reg[0]));
                                IHQUERY.setShort("p_co_pagreg", Short.parseShort(reg[2]));
                                IHQUERY.setShort("p_nu_pagfil", Short.parseShort(reg[1]));
                                IHQUERY.setString("p_va_pagreg", mv);
                                Escritor.escribe_transa("--> " + IHQUERY.getQuery());

                                IHQUERY.getMquery().uniqueResult();
                            }
                        }

                        if (propag == 1) {
                            AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfpropag"));
                            IHQUERY.setLong("p_id_frawor", id_frawor);
                            IHQUERY.setInteger("p_co_pagina", p_co_pagina);
                            IHQUERY.setShort("p_co_pagbot", p_co_pagbot);
                            IHQUERY.setInteger("p_co_conten", co_conori);
                            Escritor.escribe_frawor("@@> " + IHQUERY.getQuery());
                            IHQUERY.getMquery().uniqueResult();
                        }
                        out.print("OK");
                    } catch (Exception ep) {
                        try {
                            Transa_Engine.Transa_Ins_tbexcept(WorkflowUtil.convertir_entero("" + id_frawor), p_co_pagina, getError(ep));
                        } catch (Exception ep2) {
                            Escritor.escribe_errors("Erro al grabar la excepción:" + ep2.getMessage());
                        }
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 6: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 6">
                    String m_url = request.getParameter("url");
                    String res = "";
                    org.apache.http.HttpResponse response2 = null;
                    org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
                    org.apache.http.client.methods.HttpGet httpget = new org.apache.http.client.methods.HttpGet(m_url);
                    try {
                        response2 = client.execute(httpget);
                        org.apache.http.HttpEntity entity = response2.getEntity();
                        InputStream instream = null;
                        instream = entity.getContent();
                        res = IOUtils.toString(instream, "ISO-8859-1");
                        out.print(res);
                    } catch (Exception ep) {
                        out.print(ep);
                    }
                    // </editor-fold>
                    break;
                }
                case 7: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 7">
                    // </editor-fold>
                    break;
                }
                case 8: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 8">
                    int p_co_expedi = WorkflowUtil.convertir_entero(request.getParameter("p_co_expedi"), 0);
                    StatelessSession HSESSION = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();

                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("expedi.pbgpsselect"));
                        IHQUERY.setInteger("p_co_expedi", p_co_expedi);
                        Escritor.escribe_transa(IHQUERY.getQuery());
                        pbgpsselect o = (pbgpsselect) IHQUERY.getMquery().uniqueResult();
                        out.println(o.getPbgpsselect());
                    } catch (Exception ep) {
                        if (Transaccion.error()) {
                            throw ep;
                        }
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 9: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 9">
                    int p_co_expedi = WorkflowUtil.convertir_entero(request.getParameter("p_co_expedi"), 0);
                    String p_nu_geolat = request.getParameter("p_nu_geolat");
                    String p_nu_geolon = request.getParameter("p_nu_geolon");
                    StatelessSession HSESSION = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();

                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("expedi.pbgpsupdate"));
                        IHQUERY.setInteger("p_co_expedi", p_co_expedi);
                        IHQUERY.setString("p_nu_geolat", p_nu_geolat);
                        IHQUERY.setString("p_nu_geolon", p_nu_geolon);
                        Escritor.escribe_transa(IHQUERY.getQuery());
                        pbgpsupdate o = (pbgpsupdate) IHQUERY.getMquery().uniqueResult();
                        out.println(o.getPbgpsupdate());
                    } catch (Exception ep) {
                        if (Transaccion.error()) {
                            throw ep;
                        }
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 10: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 10">
                    String p_pw_usuari = WorkflowUtil.validar_string(request.getParameter("p_pw_usuari"), "");
                    String p_co_usulog = WorkflowUtil.validar_string(request.getParameter("p_co_usulog"), "");

                    if (WorkflowFactory.getConfiguration().isMs_login()) {
                        StatelessSession HSESSION = null;
                        try {
                            HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
                            AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("sesion.ppautent"));
                            IHQUERY.setString("p_co_usulog", p_co_usulog);
                            IHQUERY.setString("p_pw_usuari", p_pw_usuari);

                            Escritor.escribe_transa(IHQUERY.getQuery());
                            ppautent o = (ppautent) IHQUERY.getMquery().uniqueResult();
                            out.print(o.isPpautent());
                        } catch (Exception ep) {
                            Escritor.escribe_errors("[(" + WorkflowFactory.getConfiguration().isMs_login() + ") wfp:código 10][Error:" + ep.getMessage() + "]");
                            ep.printStackTrace();
                        } finally {
                            close(HSESSION);
                        }

                    } else {
                        String m_url = "http://" + WorkflowFactory.getConfiguration().getMs_host() + "/wfp?xact=10&p_pw_usuari=" + p_pw_usuari + "&p_co_usulog=" + p_co_usulog;
                        org.apache.http.HttpResponse respons = null;
                        org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
                        org.apache.http.client.methods.HttpGet httpget = new org.apache.http.client.methods.HttpGet(m_url);
                        try {
                            respons = client.execute(httpget);
                            org.apache.http.HttpEntity entity = respons.getEntity();
                            InputStream instream = entity.getContent();
                            out.print(IOUtils.toString(instream, "ISO-8859-1"));
                        } catch (IOException | IllegalStateException ep) {
                            Escritor.escribe_errors("[(" + WorkflowFactory.getConfiguration().isMs_login() + ") wfp:código 10][Error:" + ep.getMessage() + "]");
                            ep.printStackTrace();
                        }
                    }

//                    out.print("true");
                    // </editor-fold>
                    break;
                }
                case 11: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 11">
                    /**
                     * LIBRE
                     */
                    // </editor-fold>
                    break;
                }
                case 12: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 12">
                    StatelessSession HSESSION = null;
                    Transaction TRANSAX = null;
                    Query HQUERY = null;

                    int co_pagina = WorkflowUtil.convertir_entero(request.getParameter("co_pagina"), 0);
                    int co_conten = WorkflowUtil.convertir_entero(request.getParameter("co_conten"), 0);
                    short co_pagreg = WorkflowUtil.convertir_short(request.getParameter("co_pagreg"));
                    short nu_pagfil = WorkflowUtil.convertir_short(request.getParameter("nu_pagfil"));
                    String va_pagreg = request.getParameter("va_pagreg");
                    long id_frawor = WorkflowUtil.convertir_long(request.getParameter("id_frawor"));

                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();//SESSION ABIERTA
                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfins_tbpagreg"));
                        IHQUERY.setLong("p_id_frawor", id_frawor);
                        IHQUERY.setInteger("p_co_pagina", co_pagina);
                        IHQUERY.setShort("p_co_pagreg", co_pagreg);
                        IHQUERY.setShort("p_nu_pagfil", nu_pagfil);
                        IHQUERY.setString("p_va_pagreg", va_pagreg);
                        Escritor.escribe_transa("--> " + IHQUERY.getQuery());

                        IHQUERY.getMquery().uniqueResult();
                    } catch (Exception ep) {
                        throw ep;
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 13: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 13">
                    StatelessSession HSESSION = null;
                    try {
                        long p_id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                        int p_co_conten = Integer.parseInt(request.getParameter("co_conten"));
                        List l = new ArrayList();
                        String respuesta = "";

                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfget_va_conpar"));
                        IHQUERY.setLong("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_conten", p_co_conten);
                        IHQUERY.setShort("p_co_conpar", Short.parseShort("1"));
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l.add(IHQUERY.getMquery().uniqueResult());

                        IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfget_va_conpar"));
                        IHQUERY.setLong("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_conten", p_co_conten);
                        IHQUERY.setShort("p_co_conpar", Short.parseShort("2"));
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l.add(IHQUERY.getMquery().uniqueResult());

                        IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfget_va_conpar"));
                        IHQUERY.setLong("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_conten", p_co_conten);
                        IHQUERY.setShort("p_co_conpar", Short.parseShort("3"));
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l.add(IHQUERY.getMquery().uniqueResult());

                        if (l != null) {
                            Popup popup = new Popup();
                            popup.setCo_conpar_1(((pfget_va_conpar) l.get(0)).getPfget_va_conpar());
                            popup.setCo_conpar_2(((pfget_va_conpar) l.get(1)).getPfget_va_conpar());
                            popup.setCo_conpar_3(((pfget_va_conpar) l.get(2)).getPfget_va_conpar());
                            Gson g = new Gson();
                            System.out.println("GSON:\n" + g.toJson(popup));
                            out.print(g.toJson(popup));
                        } else {
                            out.print("");
                        }
                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    //----------------------------------------------------
                    // </editor-fold>
                    break;
                }
                case 14: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 14">
                    StatelessSession HSESSION = null;
                    try {
                        long p_id_frawor = Long.parseLong(request.getParameter("p_id_frawor"));
                        int p_co_conten = Integer.parseInt(request.getParameter("p_co_conten"));
                        int p_co_pagina = Integer.parseInt(request.getParameter("p_co_pagina"));
                        short p_nu_offset = Short.parseShort(request.getParameter("p_nu_offset"));

                        acceso.beans.PaginaBean paginaBean = new acceso.beans.PaginaBean(false);

                        paginaBean.setP_co_pagina(Short.parseShort("" + p_co_pagina));
                        paginaBean.setP_id_frawor(p_id_frawor);
                        paginaBean.setP_co_conten(p_co_conten);
                        paginaBean.setP_nu_offset(p_nu_offset);
                        paginaBean.setP_il_autinc(true);
                        paginaBean.setIp("0.0.0.0");
                        paginaBean.setAuxiliar("");
                        List vueltas = new ArrayList();
                        if (paginaBean.isPintado()) {
                            //fracmento pagina con data
                            for (int w = 1; w <= paginaBean.getVueltas(); w++) {
                                paginaBean.setFin(paginaBean.getIni() + paginaBean.getRegistros());
                                List tds = new ArrayList();
                                for (int e = paginaBean.getIni(); e <= paginaBean.getFin() - 1; e++) {
                                    ValregDto vregistro = (ValregDto) paginaBean.getLval().get(e);
                                    Td_autinc td = new Td_autinc();
                                    td.setCo_pagreg(vregistro.getCo_pagreg());

                                    if (vregistro.getTi_pagreg() == null) {
                                        for (int u = 0; u < paginaBean.getLreg().size(); u++) {
                                            RegistroDto reg = (RegistroDto) paginaBean.getLreg().get(u);
                                            if (reg.getId().getCo_pagreg() == vregistro.getCo_pagreg()) {
                                                td.setTi_pagreg(reg.getTi_pagreg());
                                                u = paginaBean.getLreg().size() - 1;
                                            }
                                        }
                                    } else {
                                        td.setTi_pagreg(vregistro.getTi_pagreg());
                                    }

                                    if (vregistro.getTi_estreg() == null) {
                                        for (int u = 0; u < paginaBean.getLreg().size(); u++) {
                                            RegistroDto reg = (RegistroDto) paginaBean.getLreg().get(u);
                                            if (reg.getId().getCo_pagreg() == vregistro.getCo_pagreg()) {
                                                td.setTi_estreg(reg.getTi_estreg().charAt(0));
                                                u = paginaBean.getLreg().size() - 1;
                                            }
                                        }
                                    } else {
                                        td.setTi_estreg(vregistro.getTi_estreg().charAt(0));
                                    }

                                    //td.setTi_estreg( (vregistro.getTi_estreg()==null)?'L':vregistro.getTi_estreg().charAt(0) );
                                    td.setTx_pagreg((vregistro.getTx_pagreg() == null) ? "" : vregistro.getTx_pagreg());
                                    td.setVa_pagreg((vregistro.getVa_pagreg() == null) ? "" : vregistro.getVa_pagreg());
                                    //tds.add(new Td_autinc(vregistro.getCo_pagreg(), vregistro.getTi_pagreg(), vregistro.getTi_estreg().charAt(0), vregistro.getTx_pagreg(), vregistro.getVa_pagreg()));
                                    tds.add(td);
                                }
                                paginaBean.setIni(paginaBean.getFin());
                                vueltas.add(new Tr_autinc(w, tds));
                            }
                        } else {

                        }

                        if (vueltas.size() > 0) {
                            Gson g = new Gson();
                            out.print(g.toJson(vueltas));
                        } else {
                            out.print("Lista invalida");
                        }

                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    //----------------------------------------------------
                    // </editor-fold>
                    break;
                }
                case 15: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 15">
                    long p_id_frawor = Long.parseLong(request.getParameter("p_id_frawor"));
                    int p_co_conten = Integer.parseInt(request.getParameter("p_co_conten"));
                    int p_co_pagina = Integer.parseInt(request.getParameter("p_co_pagina"));

                    acceso.beans.PaginaBean paginaBean = new acceso.beans.PaginaBean(false);

                    paginaBean.setP_co_pagina(Short.parseShort("" + p_co_pagina));
                    paginaBean.setP_id_frawor(p_id_frawor);
                    paginaBean.setP_co_conten(p_co_conten);
                    paginaBean.setP_nu_offset(Short.parseShort("0"));
                    paginaBean.setP_il_autinc(false);
                    paginaBean.setIp("0.0.0.0");
                    paginaBean.setAuxiliar("");
                    System.out.println("IS pintado!!!>>" + paginaBean.isPintado());

                    out.print("");
                    // </editor-fold>
                    break;
                }
                case 16: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 16 - Helpdesk">
                    int p_id_frawor = Integer.parseInt(request.getParameter("p_id_frawor"));
                    int p_co_conten = Integer.parseInt(request.getParameter("p_co_conten"));
                    String p_tx_conten = request.getParameter("p_tx_conten");

                    System.out.println("p_id_frawor:" + p_id_frawor);
                    System.out.println("p_co_conten:" + p_co_conten);
                    //System.out.println("p_tx_conten:"+p_tx_conten);

                    /*
                     acceso.beans.PaginaBean paginaBean = new acceso.beans.PaginaBean(false);
                        
                     paginaBean.setP_co_pagina(Short.parseShort(""+p_co_pagina));
                     paginaBean.setP_id_frawor(p_id_frawor);
                     paginaBean.setP_co_conten(p_co_conten);
                     paginaBean.setP_nu_offset(Short.parseShort("0"));
                     paginaBean.setP_il_autinc(false);
                     paginaBean.setIp("0.0.0.0");
                     paginaBean.setAuxiliar("");
                     */
                    StatelessSession HSESSION = null;
                    try {
                        //List l = new ArrayList();
                        String respuesta = "";

                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.ins_tbexcept2"));
                        IHQUERY.setInteger("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_pagina", 0);
                        IHQUERY.setString("p_no_except", "");
                        IHQUERY.setString("p_ti_except", "");
                        IHQUERY.setString("p_tx_conten", p_tx_conten);
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        IHQUERY.getMquery().uniqueResult();

                        //out.print("");
                    } catch (Exception ep) {
                        System.out.println(getError(ep));
                    } finally {
                        close(HSESSION);
                    }

                    System.out.println("IS pintado!!!>>");

                    //out.print("");
                    response.sendRedirect(request.getContextPath() + "/wf?co_conten=22");
                    // </editor-fold>
                    break;
                }
                case 17: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 17 - Helpdesk">
                    String r = "";
                    int p_id_correo = Integer.parseInt(request.getParameter("p_id_correo"));
                    try {
                        int R = ((SCorreo) Service_manager.get_servicio(0)).envia_correo(p_id_correo);
                        r = "OK";
                    } catch (Exception ep) {
                        r = "" + ep.getMessage();
                        Escritor.escribe_errors("Error:" + ep.getMessage());
                    }
                    out.print(r);
                    // </editor-fold>
                    break;
                }
                case 18: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 18 - valpagpospag">
                    StatelessSession HSESSION = null;
                    List l = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();

                        long p_id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                        int co_conten = Integer.parseInt(request.getParameter("co_conten"));
                        int p_co_pagina = Integer.parseInt(request.getParameter("co_pagina"));

                        AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfvalpagpospag"));
                        IHQUERY.setLong("p_id_frawor", p_id_frawor);
                        IHQUERY.setInteger("p_co_pagina", p_co_pagina);
                        IHQUERY.setInteger("p_co_conten", co_conten);
                        Escritor.escribe_frawor(IHQUERY.getQuery());
                        l = IHQUERY.getMquery().list();
                        if (l != null) {
                            out.print(new Gson().toJson(l));
                        } else {
                            out.print("");
                        }
                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 19: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 19 - Helpdesk">
                    StatelessSession HSESSION = null;
                    Transaction TRANSAX = null;
                    String exception = null;

                    String header = request.getHeader("Content-Type");
                    System.out.println("[header: " + header + "]");

                    long id_frawor = Long.parseLong(request.getParameter("id_frawor"));
                    int co_conten = Integer.parseInt(request.getParameter("co_conten"));
                    java.util.Enumeration enu = null;
                    try {
                        HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
                        enu = request.getParameterNames();

                        while (enu.hasMoreElements()) {
                            String o = enu.nextElement().toString();
                            String mv = request.getParameter(o);
                            if (o.startsWith("co_conpar")) {
                                AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfdel_tbconpar"));
                                IHQUERY.setLong("p_id_frawor", id_frawor);
                                IHQUERY.setInteger("p_co_conten", co_conten);
                                IHQUERY.setShort("p_co_conpar", Short.parseShort(o.replaceAll("co_conpar_", "")));
                                IHQUERY.getMquery().uniqueResult();

                                IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfins_tbconpar"));
                                IHQUERY.setLong("p_id_frawor", id_frawor);
                                IHQUERY.setInteger("p_co_conten", co_conten);
                                IHQUERY.setShort("p_co_conpar", Short.parseShort(o.replaceAll("co_conpar_", "")));
                                IHQUERY.setString("p_va_conpar", mv);
                                Escritor.escribe_frawor("--> " + IHQUERY.getQuery());
                                IHQUERY.getMquery().uniqueResult();
                            }
                        }
                        out.print("OK");
                    } catch (Exception ep) {
                        out.print(getError(ep));
                    } finally {
                        close(HSESSION);
                    }
                    // </editor-fold>
                    break;
                }
                case 20: {
                    // <editor-fold defaultstate="collapsed" desc="CASE 20 - Ubigeo">
                    String co_depart = request.getParameter("co_depart");
                    String co_provin = request.getParameter("co_provin");
                    String co_distri = request.getParameter("co_distri");
                    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
                    System.out.println("[co_depart:" + co_depart + "][co_provin:" + co_provin + "][co_distri:" + co_distri + "]");
                    if (co_depart != null) {
                        wf3.util.Departamento departamento = wf3.util.Util.findDepartamento(co_depart);
                        System.out.println("[departamento:" + departamento + "]");
                        if (co_provin != null) {
                            wf3.util.Provincia provincia = wf3.util.Util.findProvincia(departamento, co_provin);
                            if (co_distri != null) {
                                wf3.util.Distrito distrito = wf3.util.Util.findDistrito(provincia, co_distri);
                                out.print(new Gson().toJson(distrito));
                            } else {
                                out.print(gson.toJson(provincia.getDistritos()));
                            }
                        } else {
                            System.out.println("[departamento:" + departamento.getProvincias() + "]");
                            System.out.println("[departamento:" + departamento.getProvincias().size() + "]");
                            out.print(gson.toJson(departamento.getProvincias()));
                        }
                    } else {
                        out.print("");
                    }
                    // </editor-fold>
                    break;
                }
            }
        } catch (Exception ep) {
            Escritor.escribe_errors("[W]ep:" + ep.getClass() + "::" + ep.getMessage());
            request.getSession().setAttribute("Error", ep);
            response.sendRedirect("Error/contenedorError.jsp");
        } finally {
            out.close();
        }
    }

    public String getError(Exception ex) {
        String res = "";
        if (ex != null) {
            if (ex instanceof HibernateException) {
                res = ((HibernateException) ex).getMessage();
            }
            if (ex instanceof GenericJDBCException) {
                res = ((GenericJDBCException) ex).getSQLException().getMessage();
            }
            if (ex instanceof ConstraintViolationException) {
                res = ((ConstraintViolationException) ex).getSQLException().getMessage();
            }
            if (ex instanceof DataException) {
                res = ((DataException) ex).getSQLException().getMessage();
            }
            if (ex instanceof SQLGrammarException) {
                res = ((SQLGrammarException) ex).getSQLException().getMessage();
            }
            if (ex instanceof org.hibernate.exception.JDBCConnectionException) {
                res = ((org.hibernate.exception.JDBCConnectionException) ex).getSQLException().getMessage();
                if (res.indexOf("backend") > -1) {
                    res = "{El sistema esta tardando mucho en responder, por favor intentalo en unos segundos. Si este inconveniente persiste avísanos haciendo clic <a href=\"../wf?co_conten=22\">aquí</a>.}";
                }
            }

            if (res.contentEquals("")) {
                res = ex.getMessage();
            }
            int ini = res.indexOf("{");
            int fin = res.indexOf("}");
            int tipo = res.indexOf("tipo\":");
            if (ini > 0 & fin > 0 & tipo > 0) {
                res = "{" + res.substring(ini, fin + 1) + "}";
            } else if (ini > 0 & fin > 0 & tipo < 0) {
                res = "{" + res.substring(ini + 1, fin) + "}";
            }
        }
        return res;
    }

    public void close(StatelessSession session) {
        try {
            //System.out.println("================================================INI - IQARO");
            //System.out.println("session:["+session+"]");

            if (session != null) {
                try {
                    //session.close();
                    session.connection().close();
                    //System.out.println("session cerrada");
                } catch (Exception ep) {
                    session = null;
                    //System.out.println("session ["+ep.getMessage()+"]>session null");
                }
            }
            //System.out.println("================================================FIN - IQARO\n\n");
        } catch (Exception ep) {
            Escritor.escribe_errors("Error grave de hibernate: " + ep.getClass() + "\n" + ep.getMessage());
            //System.out.println("================================================FIN2 - IQARO\n\n");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
